//
//  HXDTabBarItem.swift
//  weibo
//
//  Created by huxuedong on 15/12/12.
//  Copyright © 2015年 huxuedong. All rights reserved.
//

import UIKit

class HXDTabBarItem: UITabBarItem {
    
    //重写tabBarItem的badgeValue属性
    override var badgeValue: String? {
        didSet {
            if badgeValue == nil {
                //"_target"可以看做是tabBarControlle的key，通过"_target"可以获取tabBarControlle
                let controller = valueForKeyPath("_target") as! UITabBarController
                //遍历控制器tabBar的子控件(每个按钮)
                for tabBarChild in controller.tabBar.subviews {
                    if tabBarChild.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                        //遍历每个UITabBarButton的子控件
                        for badgeViewChild in tabBarChild.subviews {
                            if badgeViewChild.isKindOfClass(NSClassFromString("_UIBadgeBackground")!) {
                                //记录_UIBadgeBackground的成员变量的个数
                                var count: UInt32 = 0
                                //获取_UIBadgeBackground的成员变量列表
                                let ivars = class_copyIvarList(NSClassFromString("_UIBadgeBackground"), &count)
                                for i in 0..<count {
                                    //取出成员变量
                                    let ivar = ivars[Int(i)]
                                    //获取成员变量的名称
                                    let name = ivar_getName(ivar)
                                    //将名称转换为字符串
                                    let nameString = NSString(CString: name, encoding: NSUTF8StringEncoding)
                                    //如果名字字符串是_image，就设置图片
                                    if nameString!.isEqualToString("_image") {
                                        badgeViewChild.setValue(UIImage(named: "main_badge"), forKey: (nameString as! String))
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
//tabBarControlle -> tabBar -> tabBarButton -> _UIBadgeBackground -> _image

}
